new Vue({
    el: '#app',
    data: {
        userAvatarUrl: '', // 用户头像URL
        username: '', // 用户名
        orders: [], // 订单列表
        filterStatus: '', // 当前筛选的订单状态
        startDate: '', // 筛选开始日期
        endDate: '', // 筛选结束日期
        searchTerm: '', // 搜索关键词
        currentPage: 1, // 当前页码
        pageSize: 5, // 每页订单数
        totalPages: 1, // 总页数
        orderTimers: {}, // 存储每个订单的定时器 
        orderCountdown: {}, // 存储每个订单的倒计时秒数 
        countdownDuration: 600, // 倒计时总时长，10分钟 = 600秒
        showPaymentModal: false, // 控制支付模态框显示
        payingOrder: null, // 当前正在支付的订单对象
        paymentPollingTimer: null, // 支付状态轮询定时器
        alipayForm: null,
        orderNo: null
    },
    methods: {
        getStatusClass(status) {
            switch (status) {
                case 0: return 'pending'; // 未支付
                case 1: return 'paid';    // 已支付
                case 2: return 'cancelled'; // 已取消
                case 3: return 'completed'; // 已完成
                default: return '';
            }
        },

        // 获取订单列表
        fetchOrders() {
            // 组织请求参数
            const params = {
                status: this.filterStatus === '' ? null : this.filterStatus, // 使用-1表示获取所有订单
                startDate: this.startDate,
                endDate: this.endDate,
                searchTerm: this.searchTerm,
                pageNum: this.currentPage,
                pageSize: this.pageSize
            };

            // 发送AJAX请求获取订单列表
            $.ajax({
                url: 'http://localhost:8080/order/findCommodityByUserId',
                type: 'POST',
                // 将请求参数转换为JSON字符串
                data: {
                    userId: localStorage.getItem('userId'),
                    status: params.status,
                    startDate: params.startDate ? new Date(params.startDate).toISOString().split('T')[0] : null,
                    endDate: params.endDate ? new Date(params.endDate).toISOString().split('T')[0] : null,
                    searchTerm: params.searchTerm,
                    page: params.pageNum,
                    pageSize: params.pageSize
                },
                headers: { 'token': `${localStorage.getItem('token') || ''}` }, // 添加token
                success: (res) => {
                    if (res) {
                        // 清除旧的定时器
                        this.clearOrderTimers();
                        this.orders = res.list.map(order => {
                            // 计算订单总金额
                            let totalAmount = (order.commodityList || []).reduce((sum, item) => {
                                const itemPrice = item.commoditySalePrice || 0;
                                const itemQuantity = item.commodityNum || 0;
                                return sum + (itemPrice * itemQuantity);
                            }, 0);

                            // 如果订单使用了优惠券，则从总金额中减去优惠券金额
                            if (order.couponAmount && order.couponAmount > 0) {
                                totalAmount -= order.couponAmount;
                            }

                            totalAmount = Math.max(0, totalAmount).toFixed(2); // 确保总金额不为负，并保留两位小数
                            // 为每个商品提取ImageUrl
                            const items = order.commodityList.map(commodity => {
                                const imageUrl ='http://localhost:8080' + (commodity.commodityPicture[0] || {}).commodityImageUrl || '';
                                return {
                                    ...commodity,
                                    imageUrl: imageUrl,
                                    countdown: order.status === 0 ? this.calculateRemainingTime(order.createTime) : 0,
                                    timer: null
                                }
                            });
                            // 为待支付订单添加倒计时相关属性
                            return {
                                ...order,
                                items: items,
                                totalAmount: parseFloat(totalAmount), // 将计算出的总金额添加到订单对象
                                countdown: order.status === 0 ? this.calculateRemainingTime(order.createTime) : 0,
                                timer: null // 独立的定时器
                            };

                        });


                        this.totalPages = res.pages;

                        // 为待支付订单启动新的定时器
                        this.startOrderTimers();


                    } else {
                        this.orders = [];
                        this.totalPages = 1;
                        console.log('获取订单列表失败:', res);
                    }
                },
                error: (xhr, status, error) => {
                    this.orders = [];
                    this.totalPages = 1;
                    console.error('AJAX error fetching orders:', status, error);
                }
            });
        },

        // 计算剩余支付时间 
        calculateRemainingTime(createTime) {
            // 确保createTime是有效的日期字符串或时间戳
            if (!createTime) return 0;
            const createTimestamp = new Date(createTime).getTime();
            const nowTimestamp = new Date().getTime();
            const elapsedSeconds = Math.floor((nowTimestamp - createTimestamp) / 1000);
            const remaining = this.countdownDuration - elapsedSeconds;
            return remaining > 0 ? remaining : 0;
        },

        // 格式化倒计时显示
        formatCountdown(seconds) {
            if (seconds <= 0) return '00:00';
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = seconds % 60;
            return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
        },

        // 启动未支付订单的倒计时
        startOrderTimers() {
            this.orders.forEach(order => {
                if (order.status === 0 && order.countdown > 0) {
                    order.timer = setInterval(() => {
                        if (order.countdown > 0) {
                            order.countdown--;
                        } else {
                            this.stopOrderTimer(order.orderId); // 倒计时结束，停止定时器
                            this.cancelOrder(order.orderId); // 取消订单
                        }
                    }, 1000);
                }
            });
        },

        // 停止单个订单的倒计时
        stopOrderTimer(orderId) {
            const order = this.orders.find(o => o.orderId === orderId);
            if (order && order.timer) {
                clearInterval(order.timer);
                order.timer = null;
            }
        },

        // 清除所有订单的定时器
        clearOrderTimers() {
            this.orders.forEach(order => {
                this.stopOrderTimer(order.id);
            });
        },

        // 取消订单
        cancelOrder(orderId) {
            if (!confirm('确定要取消此订单吗？删除后将无法恢复！')) {
                return;
            }
            $.ajax({
                url: 'http://localhost:8080/order/cancelOrder',
                type: 'GET',
                headers: { 'token': `${localStorage.getItem('token') || ''}` }, // 添加token
                data: { orderId: orderId },
                success: (res) => {
                    if (res.code === 200) {
                        // 更新订单状态为已取消
                        const orderIndex = this.orders.findIndex(o => o.orderId === orderId);
                        if (orderIndex !== -1) {
                            // 从数组中移除订单
                            this.orders.splice(orderIndex, 1);
                            alert(`订单 ${orderId} 已取消。`);
                        }
                    } else {
                        alert('订单取消失败：' + (res.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，订单取消失败');
                    console.error('AJAX error cancelling order:', status, error);
                }
            });
        },
        // 删除订单
        deleteOrder(orderId) {
            if (!confirm('确定要删除此订单吗？删除后将无法恢复！')) {
                return;
            }

            $.ajax({
                url: 'http://localhost:8080/order/deleteOrder',
                type: 'GET',
                dataType: 'json',
                data: { orderId },
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    if (res.code === 200) {
                        const orderIndex = this.orders.findIndex(o => o.orderId === orderId);
                        if (orderIndex !== -1) {
                            this.orders.splice(orderIndex, 1);
                            alert(`订单 ${orderId} 已删除。`);
                        }
                    } else {
                        alert('订单删除失败：' + (res.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，订单删除失败');
                    console.error('AJAX error deleting order:', status, error);
                }
            });
        },

        // 筛选订单状态
        filterByStatus(status) {
            this.filterStatus = status;
            this.currentPage = 1; // 筛选时重置页码
            this.fetchOrders();
        },

        // 根据日期筛选订单
        filterByDate() {
            this.currentPage = 1; // 筛选时重置页码
            if (this.startDate === '') {
                alert('开始时间或结束时间不能为空');
            } else if (this.endDate === '') {
                alert('开始时间或结束时间不能为空');
            }
            $.ajax({
                url: 'http://localhost:8080/order/findOrdersByDateRange?userId=' + localStorage.getItem('userId'),
                data: {
                    startTime: this.startDate,
                    endTime: this.endDate
                    // userId: localStorage.getItem('userId')
                },
                headers: { 'token': `${localStorage.getItem('token') || ''}` }, // 添加token
                type: 'GET',
                success: (res) => {
                    if (res) {
                        // 清除旧的定时器
                        this.clearOrderTimers();
                        this.orders = res.data.map(order => {
                            // 计算订单总金额
                            const totalAmount = (order.commodityList || []).reduce((sum, item) => {
                                const itemPrice = item.commoditySalePrice || 0;
                                const itemQuantity = item.commodityNum || 0;
                                return sum + (itemPrice * itemQuantity);
                            }, 0).toFixed(2); // 保留两位小数
                            // 为每个商品提取ImageUrl
                            const items = order.commodityList.map(commodity => {
                                const imageUrl = (commodity.commodityPicture[0] || {}).commodityImageUrl.match(/photo[\\\\/].+$/) || '';
                                return {
                                    ...commodity,
                                    imageUrl: imageUrl,
                                    countdown: order.status === 0 ? this.calculateRemainingTime(order.createTime) : 0,
                                    timer: null
                                }
                            });
                            // 为待支付订单添加倒计时相关属性
                            return {
                                ...order,
                                items: items,
                                totalAmount: parseFloat(totalAmount), // 将计算出的总金额添加到订单对象
                                countdown: order.status === 0 ? this.calculateRemainingTime(order.createTime) : 0,
                                timer: null // 独立的定时器
                            };
                        });

                        this.totalPages = res.pages;
                        // 为待支付订单启动新的定时器
                        this.startOrderTimers();

                    } else {
                        this.orders = [];
                        this.totalPages = 1;
                        console.log('获取订单列表失败:', res);
                    }
                },
                error: (xhr, status, error) => {
                    this.orders = [];
                    this.totalPages = 1;
                    console.error('AJAX error searching orders:', status, error);
                }

            })
        },

        // 搜索订单
        searchOrders() {
            // 重置页码到第一页
            this.currentPage = 1;
            this.filterStatus = 'all';
            this.fetchOrders();
        },

        // 切换分页（上一页/下一页）
        prevPage() {
            if (this.currentPage > 1) {
                this.currentPage--;
                this.fetchOrders();
            }
        },
        nextPage() {
            if (this.currentPage < this.totalPages) {
                this.currentPage++;
                this.fetchOrders();
            }
        },

        // 处理URL中的orderId参数 (从订单确认页跳转过来时)
        handleUrlOrderId() {
            const params = new URLSearchParams(window.location.search);
            const orderId = params.get('orderId');
            if (orderId) {
                // 搜索并定位到新创建的订单
                this.searchTerm = orderId;
                this.filterStatus = '未支付'; // 默认筛选待支付
                this.searchOrders(); // 调用搜索方法
            } else {
                this.fetchOrders(); // 如果没有订单ID，正常加载订单列表
            }
        },

        // 跳转到支付页面
        goToPayment(orderId) {
            const order = this.orders.find(o => o.id === orderId); // 查找对应的订单
            if (!order) {
                alert('未找到该订单信息。');
                return;
            }
            $.ajax({
                // 后端提交订单的接口
                url: 'http://localhost:8080/alipay/qrcode',
                type: 'POST',
                data: {
                    orderNo: order.orderId,
                    amount: order.totalAmount
                },
                dataType: 'json',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                success: (res) => {
                    if (res.code === 200) {
                        // 订单提交成功，生成支付二维码
                        this.alipayForm = res.data; // 获取支付宝支付表单
                        console.log('支付宝表单:', this.alipayForm);
                        this.$nextTick(() => {
                            const container = document.getElementById('alipay-container');
                            const form = container.querySelector('form'); // 在容器内查找表单
                            if (form) {
                                form.submit();
                            } else {
                                console.error('找不到 <form> 元素，请检查插入的内容是否为完整 HTML 表单');
                            }
                        });

                    } else {
                        // alert('提交订单失败：' + (res.message || '未知错误'));
                        console.log('提交订单失败：', res.message);
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，提交订单失败');
                    console.error(status, error);
                }
            });
        },

        // 开始支付状态轮询（用于模态框）
        startPaymentPolling(orderId) {
            // 先停止旧的轮询定时器
            this.stopPaymentPolling();

            const checkStatus = () => {
                // 检查模态框是否仍然显示，如果隐藏则停止轮询
                if (!this.showPaymentModal) {
                    console.log('支付模态框已关闭，停止轮询。');
                    return;
                }

                $.ajax({
                    url: `http://localhost:8080/payment/status?orderId=${orderId}`, // 假设查询支付状态的实际接口
                    type: 'GET',
                    dataType: 'json',
                    headers: { 'token': `${localStorage.getItem('token') || ''}` },
                    success: (res) => {
                        if (res.code === 200) {
                            if (res.data.status === 'PAID') {
                                // 支付成功，停止轮询，关闭模态框
                                this.stopPaymentPolling();
                                this.closePaymentModal();
                                alert('支付成功！');
                                // 可以选择刷新当前订单列表或重新获取数据
                                this.fetchOrders();
                            } else if (res.data.status === 'PENDING') {
                                // 继续轮询
                                this.paymentPollingTimer = setTimeout(checkStatus, 3000); // 每3秒查询一次
                            } else {
                                // 支付失败或其他状态，停止轮询，更新模态框信息或关闭
                                this.stopPaymentPolling();
                                alert('支付失败：' + (res.message || '未知错误'));
                                // 可以根据需要关闭模态框
                                // this.closePaymentModal();
                                // 或者更新模态框内容显示失败信息
                            }
                        } else {
                            console.error('查询支付状态失败:', res);
                            // 继续轮询，或者根据错误类型决定是否停止
                            this.paymentPollingTimer = setTimeout(checkStatus, 3000); // 继续轮询
                        }
                    },
                    error: (xhr, status, error) => {
                        console.error('AJAX error checking payment status:', status, error);
                        // 网络错误，继续轮询一段时间，或者停止
                        this.paymentPollingTimer = setTimeout(checkStatus, 3000); // 继续轮询
                    }
                });
            };

            // 延迟开始第一次轮询
            this.paymentPollingTimer = setTimeout(checkStatus, 3000);
        },

        // 停止支付状态轮询
        stopPaymentPolling() {
            if (this.paymentPollingTimer) {
                clearTimeout(this.paymentPollingTimer);
                this.paymentPollingTimer = null;
            }
        },

        // 关闭支付模态框
        closePaymentModal() {
            this.showPaymentModal = false;
            this.stopPaymentPolling(); // 停止轮询
            this.payingOrder = null; // 清除订单信息
            // 清除二维码图像
            const qrcodeEl = document.getElementById('paymentQrcode');
            if (qrcodeEl) {
                qrcodeEl.innerHTML = '';
            }
        },
        // 查看订单详情
        viewOrderDetails(orderId) {
            if (orderId) {
                window.location.href = `orderDetails.html?orderId=${orderId}`;
            } else {
                alert('无法获取订单ID，请重试。');
            }
        },
        // 添加评价
        addReview(orderId, productId) {
            console.log(`去评价：订单ID - ${orderId}，商品ID - ${productId}`);
            // 跳转到评价页面，并传递订单ID和商品ID
            window.location.href = `review.html?orderId=${orderId}&productId=${productId}`;
        },
        // 确认收货
        confirmReceipt(orderId) {
            if (!confirm('确定要确认收货吗？')) {
                return;
            }
            $.ajax({
                url: `http://localhost:8080/order/receiveOrder`,
                type: 'GET',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                data: {
                    orderId: orderId
                },
                success: (res) => {
                    if (res.code === 200) {
                        alert(`订单 ${orderId} 已确认收货！`);
                        this.fetchOrders(); // 刷新订单列表以更新状态
                    } else {
                        alert('确认收货失败：' + (res.message || '未知错误'));
                    }
                },
                error: (xhr, status, error) => {
                    alert('网络错误，确认收货失败');
                    console.error('AJAX error confirming receipt:', status, error);
                }
            });
        },
        //模糊查询订单
        searchOrders() {
            $.ajax({
                url: 'http://localhost:8080/order/searchOrdersByKeyword',
                type: 'GET',
                headers: { 'token': `${localStorage.getItem('token') || ''}` },
                data: {
                    keyword: this.searchTerm,
                    userId: localStorage.getItem('userId')
                },
                success: (res) => {
                    if (res) {
                        // 清除旧的定时器
                        this.clearOrderTimers();
                        this.orders = res.data.map(order => {
                            // 计算订单总金额
                            const totalAmount = (order.commodityList || []).reduce((sum, item) => {
                                const itemPrice = item.commoditySalePrice || 0;
                                const itemQuantity = item.commodityNum || 0;
                                return sum + (itemPrice * itemQuantity);
                            }, 0).toFixed(2); // 保留两位小数
                            // 为每个商品提取ImageUrl
                            const items = order.commodityList.map(commodity => {
                                const imageUrl = (commodity.commodityPicture[0] || {}).commodityImageUrl.match(/photo[\\\\/].+$/) || '';
                                return {
                                    ...commodity,
                                    imageUrl: imageUrl,
                                    countdown: order.status === 0 ? this.calculateRemainingTime(order.createTime) : 0,
                                    timer: null
                                }
                            });
                            // 为待支付订单添加倒计时相关属性
                            return {
                                ...order,
                                items: items,
                                totalAmount: parseFloat(totalAmount), // 将计算出的总金额添加到订单对象
                                countdown: order.status === 0 ? this.calculateRemainingTime(order.createTime) : 0,
                                timer: null // 独立的定时器
                            };
                        });

                        this.totalPages = res.pages;
                        // 为待支付订单启动新的定时器
                        this.startOrderTimers();

                    } else {
                        this.orders = [];
                        this.totalPages = 1;
                        console.log('获取订单列表失败:', res);
                    }
                },
                error: (xhr, status, error) => {
                    this.orders = [];
                    this.totalPages = 1;
                    console.error('AJAX error searching orders:', status, error);
                }
            })
        }
    },
    beforeDestroy() {
        // 组件销毁前清除所有定时器
        this.clearOrderTimers(); // 清除订单列表倒计时定时器
        this.stopPaymentPolling(); // 清除支付模态框轮询定时器
    },
    created() {
        // 在页面加载时处理URL中的订单ID或获取订单列表
        this.handleUrlOrderId();
    }
}); 